package com.eportal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.UserMsgAction;
import com.eportal.action.background.pojo.Page;
import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.base.BaseDAO;
import com.eportal.dao.TCommunityMsgEntityMapper;
import com.eportal.dao.TUserMsgEntityMapper;
import com.eportal.domain.CommunityMsg;
import com.eportal.domain.Sysopt;
import com.eportal.domain.UserMsg;
import com.eportal.entity.TCommunityMsgEntity;
import com.eportal.entity.TUserMsgEntity;
import com.eportal.params.background.TCommunitymsg.TCommunityMsgParam;
import com.eportal.service.CommunityMsgService;
import com.eportal.service.UserMsgService;
import com.eportal.util.ClobUtil;
import com.eportal.util.ValidateUtil;
import com.eportal.vo.controller.background.communitymsg.TCommunityMsgVO;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Clob;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service("userMsgService")
public class UserMsgServiceImpl  implements UserMsgService{

	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
	CommunityMsgService communityMsgService;

	@Resource
	private TCommunityMsgEntityMapper tCommunityMsgDao;

	@Resource
	private TUserMsgEntityMapper tUserMsgDao;

	private Logger log = Logger.getLogger(UserMsgServiceImpl.class);
	private Map<String, Object> result = new HashMap<String, Object>();
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Override
	public UserMsg get(Long sid){
		UserMsg userMsg = (UserMsg)dao.getById(UserMsg.class, sid);
		return userMsg;
	}
	@Override
	public CommunityMsg getCommunityMsg(Long sid) {
		CommunityMsg communityMsg = (CommunityMsg)dao.getById(CommunityMsg.class, sid);
		return communityMsg;
	}
	@Override
	public List<Map<String, Object>> list(JqGridPager jqGridPager) {
		//查社区消息表就可以了
//		String sql = "select * from t04_user_msg t";
		String sql ="select cm.sid,c.communityname,cm.cmsg,cm.receiver,TO_CHAR (cm.ctime,'yyyy-MM-dd HH24:mi:ss') as ctime from t033_community_msg cm"
				+ " left join t03_community c on cm.communityid=c.sid";
		List<Map<String, Object>> list =  dao.query(sql, jqGridPager);
		if(list.isEmpty() || list.size()<1){
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			String rUser = (String) list.get(i).get("receiver");
			if("*".equals(rUser)){
				continue;
			}else{
				String[] arrIds = rUser.split("\\|");
				final List<String> tmp2 = new LinkedList<String>();
    			for (int j = 0; j < arrIds.length; j++) {
    				tmp2.add(arrIds[j]);
				}
    			String comusql = "select auName from TUsers where userId in (:ids)";
    			List<String> listUName = dao.executeFindS(comusql,"ids",tmp2);
    			String uName = org.apache.commons.lang.StringUtils.join(listUName.toArray(),",");
    			list.get(i).put("receiver", uName);
			}
		}
		return list;
	}

	@Override
	@LogAnnotation(operateDescribe="消息通知新增")
	public Map<String, Object> addMethod(String range, String receiverId, String cMsg, String abstractMsg) {
	            try {
	            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
	            	CommunityMsg communityMsg = new CommunityMsg();
	            	Clob clob = Hibernate.createClob(cMsg);
	            	communityMsg.setCmsg(clob);
	            	if (abstractMsg.length()>100) {
	            		abstractMsg = abstractMsg.substring(0, 99)+"...";
					}
	            	communityMsg.setAbstractMsg(abstractMsg);
	            	communityMsg.setCommunityId(user.getCommunityId());
	            	communityMsg.setcTime(new Timestamp(System.currentTimeMillis()));
	            	communityMsg.setcUserName(Long.toString(user.getSid()));
	            	if("0".equals(range)){
	            		communityMsg.setReceiver("*");
						try {
							MdOpenBaseJson json = MdOpenApi.sendMsg(null,user.getCommunityId(),"community","msg_2");
		        		} catch (Exception e) {
		        			 log.info("推送消息失败",e);
		        		}
	            	}else{
	            		if(StringUtils.isBlank(receiverId)){
	            			result.put("code", 0);
	     	                result.put("msg", "无法取到要发送到人员");
	     	                return result;
	            		}
	            		communityMsg.setReceiver(receiverId.trim().replaceAll(",", "|"));
	            		try {
	            			MdOpenBaseJson json = MdOpenApi.sendMsg(receiverId.trim().replaceAll(",", "|"),null,"user","msg_2");
		        		} catch (Exception e) {
		        			 log.info("推送消息失败",e);
		        		}
	            	}
	            	communityMsg = communityMsgService.save(communityMsg);

	            	UserMsg userMsg;
	            	if ("1".equals(range)) {

	            		String[] userids= receiverId.trim().substring(1,receiverId.length()-1).split(",");
	            		for (int i = 0; i < userids.length; i++) {
	            			userMsg = new UserMsg();
	            			userMsg.setcTime(new Timestamp(System.currentTimeMillis()));
	            			userMsg.setmContent(null);
	            			userMsg.setMsgType("2");
	            			userMsg.setPublishTime(communityMsg.getcTime());
	            			userMsg.setRelateMsgId(Long.toString(communityMsg.getSid()));
	            			userMsg.setStatus("1");
	            			userMsg.setsUserId(user.getCommunityId());
							userMsg.setTipStatus("1");//待提醒
	            			userMsg.setrUserId(userids[i]);
	            			userMsg = save(userMsg);
						}
					}
	            	result.put("objectId", communityMsg.getSid());
	                result.put("code", 1);
	                result.put("msg", "操作成功");
	            } catch (Exception e) {
	                log.error("消息通知失败", e);
	                result.put("code", 0);
	                result.put("msg", "操作失败");
	            }
	        return result;
	    }

	public UserMsg save(UserMsg userMsg) throws Exception {
    	dao.save(userMsg);
    	return userMsg;
    }
	@Override
	public void addUserMsg(String content, String msgType, String ruserid, String suserid, String tipStatus) throws Exception {
		UserMsg userMsg = new UserMsg();
		userMsg.setcTime(new Timestamp(System.currentTimeMillis()));
		userMsg.setmContent(content);
		userMsg.setMsgType(msgType);
		userMsg.setPublishTime(userMsg.getcTime());
		userMsg.setRelateMsgId(null);
		userMsg.setStatus("1");
		userMsg.setsUserId(suserid);
		userMsg.setrUserId(ruserid);
		userMsg.setTipStatus(tipStatus);//待提醒
		userMsg = save(userMsg);
		return;
	}
	@Override
	public Page find(String where, Page page) {
		 StringBuffer sql = new StringBuffer("select cm.sid,cm.abstractmsg,TO_CHAR (cm.ctime,'yyyy-MM-dd HH24:mi:ss') as ctime from t033_community_msg cm"
				+ " left join t03_community c on cm.communityid=c.sid  left join t02_agtent a on c.agtcode=a.agtcode");
	        sql.append(where);
	        String countsql = "select count(*) from (" + sql.toString() + ") bb";
	        int count = dao.count(countsql);
	        if (count == 0) {
				return null;
			}
	        List<Map<String, Object>> list = dao.queryBySql("select * from (select bb.*,rownum rownum_bb from (" + sql.toString() + " order by cm.sid DESC ) bb where rownum<= " + (page.getCurrentPage() * page.getPageSize()) + ")" + " where rownum_bb>" + (page.getCurrentPage() - 1) * page.getPageSize());
	        return new Page(page.getCurrentPage(), page.getPageSize(), count, list);
	}
	@Override
	public Map<String, Object> updateMethod(String sid, String range, String receiverId, String cMsg, String abstractMsg) {
		 try {
         	Sysopt  user= (Sysopt)getSession().getAttribute("user");
         	CommunityMsg entity = getCommunityMsg(Long.parseLong(sid));
         	Clob clob = Hibernate.createClob(cMsg);
         	entity.setCmsg(clob);
         	if (abstractMsg.length()>100) {
         		abstractMsg = abstractMsg.substring(0, 99)+"...";
				}
         	entity.setAbstractMsg(abstractMsg);
         	if("0".equals(range)){
         		entity.setReceiver("*");
					try {
						MdOpenBaseJson json = MdOpenApi.sendMsg(null,user.getCommunityId(),"community","msg_2");
	        		} catch (Exception e) {
	        			 log.info("推送消息失败",e);
	        		}
         	}else{
         		entity.setReceiver(receiverId.trim().replaceAll(",", "|"));
         		try {
         			MdOpenBaseJson json = MdOpenApi.sendMsg(receiverId.trim().replaceAll(",", "|"),null,"user","msg_2");
	        		} catch (Exception e) {
	        			 log.info("推送消息失败",e);
	        		}
         	}
         	entity = communityMsgService.save(entity);

         	UserMsg userMsg;
//         	if ("1".equals(range)) {
//         		String[] userids= receiverId.trim().split(",");
//         		userMsg = new UserMsg();
//         		userMsg.setcTime(new Timestamp(System.currentTimeMillis()));
//         		userMsg.setmContent(cMsg);
//         		userMsg.setMsgType("2");
//         		userMsg.setPublishTime(communityMsg.getcTime());
//         		userMsg.setRelateMsgId(Long.toString(communityMsg.getSid()));
//         		userMsg.setStatus("1");
//         		userMsg.setsUserId(user.getCommunityId());
//         		for (int i = 0; i < userids.length; i++) {
//         			userMsg.setrUserId(userids[i]);
//         			userMsg = save(userMsg);
//					}
//				}
         	result.put("objectId", entity.getSid());
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("消息通知失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
     return result;
	}

	/**
     * 删除
     */
    @LogAnnotation(operateDescribe="公告删除")
    public Map<String, Object> deleteMethod(String sid){
    	 try {
    		 result.put("objectId", sid);
    		 delete(Long.parseLong(sid));
    		 StringBuffer sb = new StringBuffer("from UserMsg where relateMsgId=");
    		 sb.append(sid);
    		 List<UserMsg> list = dao.query(sb.toString());
    		 if (list.size()>0) {
				for (UserMsg userMsg : list) {
					 dao.delete(userMsg);
				}
			 }
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("公告删除失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
    	 return result;
    }

    public void delete(Long id) {
    	CommunityMsg communityMsg = (CommunityMsg) dao.getById(CommunityMsg.class, id);
        dao.delete(communityMsg);
	}


//todo ---------------------------------------------------------------------------------------


	/**
	 * 公告通知列表
	 *
	 * @param pageEntity 分页对象
	 * @param user       当前用户
	 * @param userRole   当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/22 下午1:28
	 * @see UserMsgServiceImpl#find(String, Page)
	 */
	@Override
	public PageInfo<TCommunityMsgVO> queryForPage(PageEntity pageEntity, Sysopt user, int userRole) {

		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}
		List<TCommunityMsgVO> list = tCommunityMsgDao.quertForList(user,userRole);
		return new PageInfo<>(list);
	}

	/**
	 * 公告详情
	 *
	 * @param sId      sId			t033_community_msg主键
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/22 下午2:58
	 * @see UserMsgAction#noticeDetailView()
	 */
	@Override
	public JSONObject noticeDetail(Long sId, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		try {
			TCommunityMsgEntity communityMsg = tCommunityMsgDao.selectByPrimaryKey(sId);
			if(communityMsg == null){
				json.put("code",0);
				json.put("msg","该记录不存在");
				json.put("data",sId);
				return json;
			}
			String msg = communityMsg.getCmsg();
//			String msg = ClobUtil.ClobToString(communityMsg.getCmsg());
			String receiver = "";
			if(communityMsg != null && StringUtils.isNotBlank(communityMsg.getReceiver())){
				receiver = communityMsg.getReceiver().replaceAll("\\|", ",");
			}

			JSONObject data = new JSONObject();
			data.put("communityMsg",communityMsg);
			data.put("communityId",communityMsg.getCommunityid());
			data.put("receiver",receiver);
			data.put("msg",msg);

			json.put("code",1);
			json.put("msg","ok");
			json.put("data",data);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			log.error("获取公告详情异常",e);
			json.put("code",0);
			json.put("msg","服务器异常");
			json.put("data",null);
			return json;
		}

	}

	/**
	 * 新增消息
	 *
	 * @param param    参数
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/22 下午4:01
	 * @see UserMsgServiceImpl#addMethod(String, String, String, String)
	 */
	@Transactional
	@Override
	public JSONObject add(TCommunityMsgParam param, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		try {

			//验证参数
			String msg = ValidateUtil.validate(param);
			if (org.apache.commons.lang3.StringUtils.isNotBlank(msg)) {
				json.put("code", 0);
				json.put("msg", msg);
				return json;
			}

			//发送范围
			String range = param.getRange();
			//消息接收人
			String receiverId = param.getReceiverId();
			//摘要
			String abstractMsg = param.getAbstractMsg();
			//消息内容
			String cMsg = param.getcMsg();

			TCommunityMsgEntity communityMsg = new TCommunityMsgEntity();
//			Clob clob = Hibernate.createClob(cMsg);
//			communityMsg.setCmsg(clob);
			communityMsg.setCmsg(cMsg);
			if (abstractMsg.length()>100) {
				abstractMsg = abstractMsg.substring(0, 99)+"...";
			}
			communityMsg.setAbstractmsg(abstractMsg);
			communityMsg.setCommunityid(user.getCommunityId());
			communityMsg.setCtime(new Timestamp(System.currentTimeMillis()));
			communityMsg.setCusername(Long.toString(user.getSid()));
			if("0".equals(range)){
				communityMsg.setReceiver("*");
				try {
					MdOpenBaseJson sendMsgResult = MdOpenApi.sendMsg(null,user.getCommunityId(),"community","msg_2");
				} catch (Exception e) {
					log.info("推送消息失败",e);
				}
			}else{
				if(StringUtils.isBlank(receiverId)){
					json.put("code", 0);
					json.put("msg", "无法取到要发送到人员");
					return json;
				}
				communityMsg.setReceiver(receiverId.trim().replaceAll(",", "|"));
				try {
					MdOpenBaseJson sendMsgResult = MdOpenApi.sendMsg(receiverId.trim().replaceAll(",", "|"),null,"user","msg_2");
				} catch (Exception e) {
					log.info("推送消息失败",e);
				}
			}
			tCommunityMsgDao.insertSelective(communityMsg);

			if ("1".equals(range)) {

				TUserMsgEntity userMsg;

				String[] userids= receiverId.trim().substring(1,receiverId.length()-1).split(",");
				for (int i = 0; i < userids.length; i++) {
					userMsg = new TUserMsgEntity();
					userMsg.setCtime(new Timestamp(System.currentTimeMillis()));
					userMsg.setMcontent(null);
					userMsg.setMsgType("2");
					userMsg.setPublishTime(communityMsg.getCtime());
					userMsg.setRelateMsgId(Long.toString(communityMsg.getSid()));
					userMsg.setStatus("1");
					userMsg.setSuserid(user.getCommunityId());
					userMsg.setTipStatus("1");//待提醒
					userMsg.setRuserid(userids[i]);
					tUserMsgDao.insertSelective(userMsg);
				}
			}
			json.put("objectId", communityMsg.getSid());
			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("data",communityMsg.getSid());
			return json;
		} catch (Exception e) {
			log.error("消息通知失败", e);
			json.put("code", 0);
			json.put("msg", "操作失败");
			return json;
		}
	}

	/**
	 * 删除消息
	 *
	 * @param sId      sId			t033_community_msg主键
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/22 下午6:06
	 * @see UserMsgServiceImpl#deleteMethod(String)
	 */
	@Override
	public JSONObject delete(Long sId, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		try {
			result.put("objectId", sId);
			//删除社区信息
			tCommunityMsgDao.deleteByPrimaryKey(sId);
			//删除住户信息
			tUserMsgDao.deleteByRelateMsgId(sId);
			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("data",sId);
			return json;
		} catch (Exception e) {
			log.error("公告删除失败", e);
			json.put("code", 0);
			json.put("msg", "操作失败");
			return json;
		}
	}
}
